var app = getApp();
var that;

Page({

  data: {
    tabstyle: 'background-image: linear-gradient(to top, #fff 0%, #badef8 10%,#9bd1f8 20%, #71bdf3 30%, #57a7f1 40%, #55aff0 60%, #3797ee 80%, #1885e8 100%)',
    navBar: [{
      label: '代取快递',
      active: true
    }, {
      label: '代寄快递',
      active: false
    }, {
      label: '跑腿代办',
      active: false
    }],
    navBar2: [{
      label: '小件',
      active: true
    }, {
      label: '中件',
      active: false
    }, {
      label: '大件',
      active: false
      }, {
        label: '特大件',
        active: false
      }],
    tab:'代取快递',
    tab2: '小件',
    btnloading: false,
    address: { schoolName: '请选择默认地址', name:'暂无默认信息' },
    sliderMin: 0,
    money: 0,
    content: '',
    remark: '',
    times: 0,
    payType: ['微信支付', '钱包支付'],
    payName: '微信支付',
    userMoney: 0,
    formIdString: ''
  },

  // 选择到店自取还是外卖上楼
  changeBar: function (e) {
    for (var i = 0; i < that.data.navBar.length; i++) {
      that.data.navBar[i].active = false;
    }
    let index = e.currentTarget.dataset.index;
    that.data.navBar[index].active = true
    if (index == 0) {
      that.data.tab = '代取快递'
      that.data.tabstyle = 'background-image: linear-gradient(to top, #fff 0%, #badef8 10%,#9bd1f8 20%, #71bdf3 30%, #57a7f1 40%, #55aff0 60%, #3797ee 80%, #1885e8 100%)'
    } else if (index == 1) {
      that.data.tab = '代寄快递'
      that.data.tabstyle = 'background-image: linear-gradient(to top, #fff 0%, #fdbbb1 10%, #fe9a8b 20%, #fe9a8b 30%, #fd868c 40%, #f9748f 60%, #f78ca0 100%)'
    } else {
      that.data.tab = '跑腿代办'
      that.data.tabstyle = 'background-image: linear-gradient(to top, #fff 0%, #cbeceb 10%, #a1e7e4 20%, #b1ece9 30%, #8ee0dc 40%, #50c9c3 60%, #37b6af 100%)'
    }
    that.setData({
      navBar2: [{
        label: '小件',
        active: true
      }, {
        label: '中件',
        active: false
      }, {
        label: '大件',
        active: false
      }, {
        label: '特大件',
        active: false
      }],
      tab2: '小件',
      money: wx.getStorageSync("school").smallMinAmount,
      sliderMin: wx.getStorageSync("school").smallMinAmount,
      content: '',
      remark: '',
      tabstyle: that.data.tabstyle,
      navBar: that.data.navBar,
      tab: that.data.tab
    })
  },

  // 选择到店自取还是外卖上楼
  changeBar2: function (e) {
    for (var i = 0; i < that.data.navBar2.length; i++) {
      that.data.navBar2[i].active = false;
    }
    let index = e.currentTarget.dataset.index;
    that.data.navBar2[index].active = true
    if (index == 0) {
      that.data.tab2 = '小件';
      that.data.money = wx.getStorageSync("school").smallMinAmount;
      that.data.sliderMin = wx.getStorageSync("school").smallMinAmount;
    } else if (index == 1) {
      that.data.tab2 = '中件';
      that.data.money = wx.getStorageSync("school").middleMinAmount;
      that.data.sliderMin = wx.getStorageSync("school").middleMinAmount;
    } else if (index == 2) {
      that.data.tab2 = '大件'
      that.data.money = wx.getStorageSync("school").largeMinAmount;
      that.data.sliderMin = wx.getStorageSync("school").largeMinAmount;
    } else {
      that.data.tab2 = '特大件'
      that.data.money = wx.getStorageSync("school").extraLargeMinAmount;
      that.data.sliderMin = wx.getStorageSync("school").extraLargeMinAmount;
    }
    that.setData({
      navBar2: that.data.navBar2,
      tab2: that.data.tab2,
      money: that.data.money,
      sliderMin: that.data.sliderMin
    })
  },

  onLoad: function (options) {
    that = this;
    that.data.times = that.haveSomeMinutesTime(30);
    that.setData({
      tim: that.data.times,
      times: that.data.times,
    })
  },

  onShow: function () {
    this.initAddress();
    if (wx.getStorageSync("payName") == '钱包支付') {
      that.setData({
        payName: '钱包支付'
      })
    } else if (wx.getStorageSync("payName") == '微信支付') {
      that.setData({
        payName: '微信支付'
      })
    }
    that.setData({
      userMoney: wx.getStorageSync("userMoney"),
      sliderMin: wx.getStorageSync("school").smallMinAmount,
      money: wx.getStorageSync("school").smallMinAmount,
    })
  },

  //缓存如果有默认地址拿出来用
  initAddress: function () {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    if (wx.getStorageSync("defaultAddress")) {
      //获取楼栋地址
      app.post('/ops/floor/find', {
        page: 1,
        size: 1000,
        schoolId: wx.getStorageSync("schoolId")
      }, function (res) {
        if (res.data.code) {
          var num = -1
          for (let i = 0; i < res.data.params.list.length; i++) {
            if (res.data.params.list[i].id == wx.getStorageSync("defaultAddress").floorId) {
              num = i
            }
          }
          if (num != -1) {
            that.setData({
              address: wx.getStorageSync("defaultAddress"),
              floorId: res.data.params.list[num].id,
            })
            wx.hideLoading()
          } else {
            wx.hideLoading()
            wx.showModal({
              title: '提示',
              content: '默认地址的信息已失效，请重新设置默认地址',
              showCancel: false,
              confirmColor: '#3797ee',
              confirmText: '前往设置',
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/mine/location/location?type=1',
                  })
                }
              }
            })
          }
        } else {
          wx.hideLoading()
        }
      })
    } else {
      wx.hideLoading()
    }
  },

  // 代跑事项
  contactshixiang: function (e) {
    that.setData({
      content: e.detail.value
    })
  },

  //备注信息
  contactbeizhu: function (e) {
    that.setData({
      remark: e.detail.value
    })
  },

  // 选择预计时间 
  bindTimeChange: function (e) {
    that.setData({
      times: e.detail.value
    })
  },

  //选择支付方式
  bindPickerChange: function (e) {
    that.setData({
      payName: that.data.payType[e.detail.value],
    })
  },

  //跳转到我的界面的地址界面
  moreCusInfo: function () {
    wx.navigateTo({
      url: '/pages/mine/location/location?type=1',
    })
  },

  //相应时间
  haveSomeMinutesTime: function (n) {
    var newDate = new Date()
    var date = newDate.setMinutes(newDate.getMinutes() + n);
    newDate = new Date(date);
    var h = newDate.getHours();
    var m = newDate.getMinutes();
    if (h < 10) {
      h = '0' + h;
    };
    if (m < 10) {
      m = '0' + m;
    };
    var time = h + ':' + m;
    return time;
  },

  //滑块函数
  sliderchange: function (e) {
    that.setData({
      money: e.detail.value
    })
  },

 //减
  disaddCart:function(){
    if (that.data.sliderMin == that.data.money ){
      wx.showToast({
        title: "至少" + that.data.sliderMin + '元起',
        image: '/images/tanHao.png',
        duration: 1000,
        mask: true
      })
    }else{
      that.data.money--;
      that.setData({
        money: that.data.money
      })
    }
  },
  
  //加
  addCart: function () {
    if (that.data.money == 100) {
      wx.showToast({
        title: "最多100跑腿费",
        image: '/images/tanHao.png',
        duration: 1000,
        mask: true
      })
    } else {
      that.data.money++;
      that.setData({
        money: that.data.money
      })
    }
  },



  saveFormId: function (e) {
    this.setData({
      formIdString: e.detail.formId
    })
  },
  //提交函数
  formSubmit: function (e) {
    var formIds = e.detail.formId + ',' + that.data.formIdString
    if (that.data.address.schoolName == "请选择默认地址" || that.data.content == "" || that.data.remark == "") {
        wx.showToast({
          title: "请输入完整信息",
          image: '/images/tanHao.png',
          duration: 2000,
          mask: true
        })
      } else if (that.data.payName == '钱包支付') {
        if (that.data.userMoney < that.data.money) {
          wx.showModal({
            title: '提示',
            content: '余额不足，立即前往充值',
            showCancel: true,
            confirmColor: '#3797ee',
            confirmText: '前往充值',
            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/mine/payment/payment',
                })
              }
            }
          })
        } else {
          that.orderPay(formIds)
        }
      } else {
        that.orderPay(formIds)
      }
  },

  orderPay: function (formIds) {
    that.setData({
      btnloading: true
    })
    //下单
    let content = that.data.tab == '跑腿代办' ? that.data.content : that.data.remark + '：' + that.data.content
    let remark = that.data.tab == '跑腿代办' ? that.data.remark : that.data.tab + that.data.tab2
    app.post('/ops/runorders/add', { 
      totalPrice: that.data.money, 
      addressName: that.data.address.name, 
      addressPhone: that.data.address.phone, 
      addressDetail: that.data.address.schoolName + ',' + that.data.address.floorName + ',' + that.data.address.detail, 
      content: content, 
      reserveTime: that.data.times, 
      remark: remark, 
      floorId: that.data.address.floorId, 
      schoolId: wx.getStorageSync("schoolId") 
      }, function (res) {
      if (res.data.code) {
        //成功
        that.setData({
          orderId: res.data.msg
        })
        if (that.data.payName == '钱包支付') {
          wx.setStorageSync('payName', '钱包支付');
          app.post("/ops/runorders/pay", {
            orderId: res.data.msg,
            payment: '余额支付',
            formid: formIds
          }, function (res) {
            if (res.data.code) {
              that.setData({
                btnloading: false
              })
              wx.redirectTo({
                url: "/pages/order/orderSuccess/orderSuccess?orderId=" + that.data.orderId + '&typ=' + '跑腿订单'
              })
            } else {
              that.setData({
                btnloading: false
              })
              wx.showModal({
                title: '提示',
                content: res.data.msg,
                showCancel: false,
                confirmColor: '#3797ee',
                confirmText: '确定',
                success: function (res) {
                  if (res.confirm) {
                    wx.redirectTo({
                      url: "/pages/order/orderDetail/orderDetail?orderId=" + that.data.orderId + '&typ=' + '跑腿订单'
                    })
                  }
                }
              })
            }
          })
        } else {
          wx.setStorageSync('payName', '微信支付');
          app.post("/ops/runorders/pay", {
            orderId: res.data.msg,
            payment: '微信支付',
            formid: formIds
          }, function (res) {
            if (res.data.code) {
              let msg = res.data.params.msg;
              wx.requestPayment({
                timeStamp: msg.time,
                nonceStr: msg.nonceStr,
                package: 'prepay_id=' + msg.prepay_id,
                signType: 'MD5',
                paySign: msg.paySign,
                success: function (res) {
                  that.setData({
                    btnloading: false
                  })
                  wx.redirectTo({
                    url: "/pages/order/orderSuccess/orderSuccess?orderId=" + that.data.orderId + '&typ=' + '跑腿订单'
                  })
                },
                fail: function () {
                  that.setData({
                    btnloading: false
                  })
                  wx.redirectTo({
                    url: "/pages/order/orderDetail/orderDetail?orderId=" + that.data.orderId + '&typ=' + '跑腿订单'
                  })
                }
              })
            }else{
              that.setData({
                btnloading: false
              })
              wx.showModal({
                title: '提示',
                content: res.data.msg,
                showCancel: false,
                confirmColor: '#3797ee',
                confirmText: '确定',
                success: function (res) {
                  if (res.confirm) {
                    wx.redirectTo({
                      url: "/pages/order/orderDetail/orderDetail?orderId=" + that.data.orderId + '&typ=' + '跑腿订单'
                    })
                  }
                }
              })
            }
          })
        }
      } else {
        that.setData({
          btnloading: false
        })
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000,
          mask: true,
        })
      }
    })
  },
  
  //转发后显示的内容
  onShareAppMessage: function () {
    return {
      title: '快来和我一起享校园品质生活吧！！',
      path: '/pages/index/index',
    }
  },
})